package com.crmweb.controller;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.crmweb.dto.TreeModules;
import com.crmweb.entity.Askers;
import com.crmweb.entity.PageVo;
import com.crmweb.entity.Result;
import com.crmweb.entity.Roles;
import com.crmweb.entity.Userroles;
import com.crmweb.entity.Users;
import com.crmweb.service.AskersService;
import com.crmweb.service.RolesService;
import com.crmweb.service.UsersService;
import com.crmweb.tool.CommonUtil;
import com.crmweb.tool.ConstantUtil;

@RestController
public class UsersController {

	@Resource
	private UsersService us;
	@Resource 
	private AskersService as;
	
	
	@RequestMapping(value="/login",method = RequestMethod.POST)
	//@RequestMapping("/login")
	public Map<String, Object> loginByName( HttpServletRequest request){
		Map<String, Object> mapuser = new HashMap<String, Object>();
		
		/*
		 * DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Timestamp
		 * lastLoginTime = Timestamp.valueOf(df.format(new Date()));
		 */
		String name = request.getParameter("username");
		String pwd = request.getParameter("password");
		//System.out.println(name);
		//System.out.println(pwd);
		try {
			Users user = us.login(name, pwd);
		//	System.out.println(user.getLoginName());
			if(user !=null) {
				if(user.getPassword().equals(pwd)) {
					if(user.getIsLockOut().equals("是")) {
						//System.out.println("suoding--------------------------------");
						mapuser.put("isluck", true);
					}
					else {
						HttpSession session	=request.getSession(true);
						session.setMaxInactiveInterval(3600);// session过期时间3600秒
						session.setAttribute(ConstantUtil.USERS, user);
						String userid = user.getId();
						mapuser.put("logins", true);
						us.updateLastLoginTime(userid);
						
						mapuser.put("user", user);

					}
					
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return mapuser;
		
		
	}
	
	
	/** 用户退出 */
	@RequestMapping("loginOut")
	//@ResponseBody
	public Map<String, Object> loginOut(HttpServletRequest request) {
		Map<String, Object> resultMap = CommonUtil.getResultMap();
		try {
			// 退出时清空session保存的用户信息
			HttpSession session = request.getSession();
//			session.removeAttribute(ConstantUtil.USERID);
//			session.removeAttribute(ConstantUtil.USERNAME);
			session.removeAttribute(ConstantUtil.USERS);

			resultMap.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}
	
	
	@RequestMapping("sys/checkLoginName")
	//@ResponseBody
	public Object checkName(HttpServletRequest request) {
		String loginName=request.getParameter("loginName");
	//	System.out.println("--------------------------------------------------------"+loginName);
		List<String> uname=us.findAllName();
	
		if(uname.contains(loginName)) {
			Result result=new Result("","",true);
			return result;
		}else {
			Result result=new Result("","",false);
			return result;
		}
	}
	@RequestMapping("checkLoginName")
	//@ResponseBody
	public Object checkNames(HttpServletRequest request) {
		String loginName=request.getParameter("loginName");
	//	System.out.println("--------------------------------------------------------"+loginName);
		List<String> uname=us.findAllName();
	
		if(uname.contains(loginName)) {
			Result result=new Result("","",true);
			return result;
		}else {
			Result result=new Result("","",false);
			return result;
		}
	}
	
	
//	//查询树
//	@RequestMapping("/queryTree")
//	//@ResponseBody
//	public Object queryTree(HttpServletRequest request) {
//		
//		HttpSession session=request.getSession(); 
//		Users users=(Users)session.getAttribute(ConstantUtil.USERS);
//		Map<String, Object> map = new HashMap<>();
//			List<TreeModules> list=us.queryModulesTreeNodes(users);
//			List<TreeModules> nodes=us.queryModel(list);
//			return nodes;
//
//		
//
//		
//	}
	//多条件分页查询用户信息
	@RequestMapping("sys/showAllByWhere")
	public Map<String, Object> showAllByWhere(HttpServletRequest request){
		
		String name = request.getParameter("name");
		/*
		 * String emile = request.getParameter("emile"); String tel =
		 * request.getParameter("tel");
		 */
		String sort = request.getParameter("sort");
		String btime = request.getParameter("btime");
		String etime = request.getParameter("etime");
		String islock = request.getParameter("islock");
		String page = request.getParameter("page");
		String pagesize = request.getParameter("limit");
		
		
		Users user = new Users();
		if(name != null && name !="") {
			user.setLoginName(name);
			
		}
		if(islock != null && islock != "") {
			
			user.setIsLockOut(islock);
		}
		/*
		 * if ( emile != null && emile!="") { user.setProtectEmail(emile); } if ( tel !=
		 * null && tel !="") { user.setProtectMTel(tel); }
		 */
		if ( sort != null && sort !="") {
			user.setBycrte(sort);;
		}
		if ( btime != null && btime !="") {
			user.setBtime(btime);
		}
		if (etime  != null && etime !="") {
			user.setEtime(etime);
		}
		PageVo vo = new PageVo();
		vo.setPage(Integer.parseInt(page));
		vo.setPageSize(Integer.parseInt(pagesize));
		user.setVo(vo);
		List<Users> list = us.showAllByWhere(user);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", 0);
		map.put("data", list);
		map.put("count", us.getCount(user));
		
		return map;
		
	}
	
	//添加用户
		@RequestMapping("sys/addUser")
		public Object  addUser(Users user,HttpServletRequest request){
			int i =us.addUser(user);
			if(i>0) {
				Result res = new Result("添加成功","",true);
				return res;
			}else {
				Result res = new Result("添加失败","",false);
				return res;
			}
		}
		//修改用户
		//重置密码
				@RequestMapping("sys/updUser")
				public Object  updUser(Users user,HttpServletRequest request){
					int i =us.updUser(user);
					if(i>0) {
						Result res = new Result("修改成功","",true);
						return res;
					}else {
						Result res = new Result("修改失败","",false);
						return res;
					}
				}
				//删除用户
				@RequestMapping("sys/delUser")
				public Object  delUser(HttpServletRequest request){
					String id= request.getParameter("id");
					List<String> list = us.selRoleIdByUid(id);
					for (String string : list) {
						//System.out.println("---------------"+string);
					}
					Result res = new Result();
					if(list.size()<1) {
						int i = us.delUser(id);
						if(i>0) {
							 res = new Result("删除成功","",true);
						//	return res;
						}else {
							 res = new Result("删除失败","",false);
						//	return res;
						}
					}else {
						 res = new Result("该用户已被分配角色，如果删除的话请先删除该用户的所有角色","",true);
					}
						
					
					return res;
					
				}
				//解除锁定
				@RequestMapping("sys/deblockUser")
				public Object  deblockUser(HttpServletRequest request){
					String id= request.getParameter("id");
					int i =us.deblockUser(id);
					if(i>0) {
						Result res = new Result("解除锁定成功","",true);
						return res;
					}else {
						Result res = new Result("解除锁定失败","",false);
						return res;
					}
				}
				//锁定
				@RequestMapping("sys/blockUser")
				public Object  blockUser(HttpServletRequest request){
					String id= request.getParameter("id");
					int i =us.blockUser(id);
					if(i>0) {
						Result res = new Result("锁定用户成功","",true);
						return res;
					}else {
						Result res = new Result("锁定用户失败","",false);
						return res;
					}
				}
				@Resource
				private RolesService rs;
				//查询用户角色
				@RequestMapping("sys/selRolesByUser")
				public Map<String, Object> selRolesByUser(HttpServletRequest request){
					String id = request.getParameter("id");
					List<Roles> list = rs.getRolesByUserId(id);
					Map<String, Object> map = new HashMap<>();
					map.put("code", 0);
					map.put("data", list);
					map.put("count", list.size());
					return map;
				}
				//添加用戶角色
				@RequestMapping("sys/addRolersToUser")
				public Object addRolersToUser(HttpServletRequest request) {
					String ids = request.getParameter("ids");
					String uid = request.getParameter("id");
//					System.out.println(ids);
//					String[] rid = ids.split(",");
					List<Userroles> yrlist = new ArrayList<>();
					//System.out.println("-------------rid:"+rid.length);
					
					//用户已有角色
					
					List<String> list = us.selRoleIdByUid(uid);
				//	Result	res = new Result();
					//if(list.size()>0) {
					 // if(rid.length<=1) {
					  if(list.size()>0) {
						  for(int z =0;z<list.size();z++) {
							  Userroles ur = new Userroles();
							  
							 // if(list.get(z).equals(rid[0])) {
							  if(list.get(z).equals(ids)) {
								  Result 	res = new Result("該角色已存在，請勿重複添加","",false);
								  	//rid=null;
								return res;
							  }else {
								   ur.setRoleId(ids);
									ur.setUserId(uid);
									yrlist.add(ur);
									int j = us.addRolersToUser(yrlist);
									if(j>0) {
										//判断添加的是否是咨询师角色 是的话就在askers表中插入一条咨询师信息
										Roles roles = us.selRoleByRoleId(ids);
										if(roles != null&& roles.getName().equals("咨询师")) {
											//是咨询师角色  就将用户信息插入到咨询师信息
											Users users = us.selUsersByUid(uid);
											Askers asker = new Askers();
											asker.setAskerId(users.getId());
											asker.setAskerName(users.getLoginName());
											as.addAskers(asker);
										}
										
										Result	res = new Result("设置角色成功","",true);
											//rid=null;
										return res;
									}else {
										Result  res = new Result("设置角色失败","",false);
										  //rid=null;
										return res;
									}
							  }
						  }
					  }else {
						  
						    Userroles ur = new Userroles();
						    ur.setRoleId(ids);
							ur.setUserId(uid);
							yrlist.add(ur);
							int j = us.addRolersToUser(yrlist);
							if(j>0) {
								Result	res = new Result("设置角色成功","",true);
									//rid=null;
								return res;
							}else {
								Result  res = new Result("设置角色失败","",false);
								//  rid=null;
								return res;
					  }
					  }
					  
					return null;
						 
//					  }else if(rid.length>1){
//						  for (int i=0;i<list.size();i++) {
//								//if(rid[i] !="" && rid[i] !=null) {
//									if(list.get(i).contains(rid[i])) {
//										//us.addRolersToUser(rid);
//										res = new Result("添加失敗,請查看是否有重複添加","",false);
//										rid=null;
//										return res;
//									}else {
//											Userroles ur = new Userroles();
//												ur.setRoleId(rid[i]);
//												System.out.println("--------------"+rid[i]);
//												ur.setUserId(uid);
//												yrlist.add(ur);
//									}
//							//}
//						  }
//						  int s = us.addRolersToUser(yrlist);
//							if(s>0) {
//								res = new Result("设置角色成功","",true);
//								rid=null;
//							return res;
//						}else {
//							   res = new Result("设置角色失败","",false);
//							   rid=null;
//							return res;
//						}
//					  }
						
						
//					}else {
//						
//					//	for (int i=0;i<rid.length;i++) {
//							Userroles ur = new Userroles();
//								ur.setRoleId(rid[0]);
//								System.out.println("--------------"+rid[0]);
//								ur.setUserId(uid);
//								yrlist.add(ur);
//							
//							//}
//					//	System.out.println("-------------yrlist:"+yrlist.size());
//						int i = us.addRolersToUser(yrlist);
//						if(i>0) {
//								res = new Result("设置角色成功","",true);
//								rid=null;
//							return res;
//						}else {
//							   res = new Result("设置角色失败","",false);
//							   rid=null;
//							return res;
//						}
//				}
					
		}
				
				//刪除用戶角色
				@RequestMapping("sys/delRolesByUser")
		public Object delRolesByUser(HttpServletRequest request) {
					String ids = request.getParameter("ids");
					String uid = request.getParameter("id");
					int i = us.delRolesByUser(uid, ids);
					//Result	res = new Result("刪除角色失敗","",false);
					if(i>0) {
						Result	res = new Result("刪除角色成功","",true);
					return res;
				}else {
						Result   res = new Result("刪除角色失败","",false);
					return res;
				}
					//return uid;
			}
				//判断原密码是否正确
				@RequestMapping("checkPassword")
				public Object checkPassword(HttpServletRequest request) {
					String pwd = request.getParameter("pwd");
					HttpSession session = request.getSession();
					Users user = (Users) session.getAttribute(ConstantUtil.USERS);
					if(pwd.equals(user.getPassword())) {
						Result	res = new Result("","",true);
						return res;
					}else {
							Result   res = new Result("","",false);
							return res;
					}
					
				}
				//修改密码
				@RequestMapping("updPassword")
				public Object updPassword(HttpServletRequest request) {
					String pwd = request.getParameter("pwd");
					//System.out.println("------------------"+pwd);
					HttpSession session = request.getSession();
					Users user = (Users) session.getAttribute(ConstantUtil.USERS);
					String uid = user.getId();
					int i = us.updPassword(pwd, uid);
					if(i>0) {
							Result	res = new Result("修改密码成功","",true);
							return res;
					}else {
							Result   res = new Result("修改密码失败","",false);
							return res;
					}
					
				}
				
}
